<template>
  <div>
    <vxe-toolbar ref="toolbarRef" custom></vxe-toolbar>
    <vxe-table id="patientTable" class="oper-table" ref="patientTableRef" :data="props.patients" height="100%"
      min-height="400px" max-height="85vh" auto-resize show-overflow :scroll-y="{ enabled: true }" :custom-config="{}"
      :column-config="{}" :row-config="{ isCurrent: true, isHover: true }" :seq-config="{ startIndex: 0 }"
      :edit-config="{ mode: 'cell', trigger: 'dblclick' }" size="mini" border fixed fit resizable highlight-current-row
      highlight-hover-row keep-source :column-drag-sort="true" header-align="center">
      <vxe-column field="bedNumber" title="床位号" width="100"></vxe-column>
      <vxe-column field="patientName" title="姓名" width="100"></vxe-column>
      <vxe-column field="gender" title="性别" width="60"></vxe-column>
      <vxe-column field="age" title="年龄" width="60"></vxe-column>
      <vxe-column field="diagnosis" title="诊断" min-width="150"></vxe-column>
      <vxe-column field="doctor" title="主治医生" width="100"></vxe-column>
      <vxe-column field="nurse" title="责任护士" width="100"></vxe-column>
      <vxe-column field="admissionDate" title="入科时间" width="120"></vxe-column>
      <vxe-column field="daysIn" title="天数" width="80"></vxe-column>
      <vxe-column field="status" title="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="280" align="center">
        <template #default="{ row }">
          <div style="display: flex; gap: 8px">
            <template v-if="row.status === '空闲'">
              <el-button type="primary" size="small" @click="admitPatient(row)" plain>
                <template #icon>
                  <font-awesome-icon :icon="['fas', 'sign-in-alt']" />
                </template>
                患者入科
              </el-button>
            </template>
            <template v-else>
              <el-button type="primary" size="small" @click="scanCode(row)" plain>
                <template #icon>
                  <font-awesome-icon :icon="['fas', 'qrcode']" />
                </template>
                扫码
              </el-button>
              <el-button type="warning" size="small" @click="transferBed(row)" plain>
                <template #icon>
                  <font-awesome-icon :icon="['fas', 'exchange-alt']" />
                </template>
                转床
              </el-button>
              <el-button type="danger" size="small" @click="discharge(row)" plain>
                <template #icon>
                  <font-awesome-icon :icon="['fas', 'sign-out-alt']" />
                </template>
                患者出科
              </el-button>
            </template>
          </div>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { VxeToolbarInstance, VxeTableInstance } from 'vxe-table'
const props = defineProps<{
  patients: Array<{
    id: string
    bedNumber: string
    patientId: string
    patientName: string
    gender: string
    age: number
    caseNumber: string
    diagnosis: string
    surgery: string
    allergy: string
    doctor: string
    nurse: string
    admissionDate: string
    daysIn: number
    criticalLevel: number
    status: string
  }>
}>()
onMounted(() => {
  const $table = patientTableRef.value
  const $toolbar = toolbarRef.value
  if ($table && $toolbar) {
    $table.connect($toolbar)
  }
})
interface RowVO {
  id: string
  bedNumber: string
  patientId: string
  patientName: string
  gender: string
  age: number
  caseNumber: string
  diagnosis: string
  surgery: string
  allergy: string
  doctor: string
  nurse: string
  admissionDate: string
  daysIn: number
  criticalLevel: number
  status: string
}
const toolbarRef = ref<VxeToolbarInstance>()
const patientTableRef = ref<VxeTableInstance>()

const printData = async () => {
  try {
    console.log('正在准备打印患者数据...')
    const $grid = patientTableRef.value
    if (!$grid) {
      throw new Error('表格实例未初始化')
    }
    if (!props.patients?.length) {
      throw new Error('没有可打印的患者数据')
    }

    const printOptions = {
      sheetName: '患者信息表',
      style: `
        .vxe-table--print-element {
          font-size: 14px;
        }
        .vxe-table--print-title {
          text-align: center;
          font-size: 18px;
          font-weight: bold;
          margin-bottom: 20px;
        }
      `
    }
    console.log('打印配置:', printOptions)

    // 检查打印功能是否可用
    if (typeof $grid.print !== 'function') {
      throw new Error('当前vxe-table版本不支持打印功能')
    }

    const result = await $grid.print(printOptions)
    console.log('打印结果:', result)

    if (result && typeof result === 'object' && result.status === false) {
      const errMsg = result.errMsg || result.message || '打印被取消或失败'
      console.error('打印失败详情:', {
        result,
        printOptions,
        error: errMsg
      })
      throw new Error(errMsg)
    }

    if (!result) {
      throw new Error('打印未返回有效结果')
    }

    console.log('打印成功:', result)
    ElMessage.success('正在打开打印预览...')
  } catch (err) {
    let errorMsg = '打印过程中发生未知错误'

    // 处理错误对象
    if (err && typeof err === 'object') {
      if (err instanceof Error) {
        errorMsg = err.message
      } else if ('status' in err) {
        errorMsg = err.status === false ? '打印操作被拒绝' : `打印状态: ${err.status}`
      }
    }

    // 默认错误消息
    errorMsg = errorMsg || '打印过程中发生未知错误'

    console.error('打印错误:', {
      time: new Date().toISOString(),
      errorType: err?.constructor?.name || typeof err,
      errorDetails: err
    })

    ElMessage.error(`打印失败: ${errorMsg}`)
  }
}

const emit = defineEmits<{
  (e: 'current-change', row: RowVO): void
  (e: 'admit', row: RowVO): void
  (e: 'scan', row: RowVO): void
  (e: 'transfer', row: RowVO): void
  (e: 'discharge', row: RowVO): void
}>()

const getStatusType = (status: string) => {
  switch (status) {
    case '危重': return 'danger'
    case '普通': return 'primary'
    case '出院': return 'success'
    default: return 'info'
  }
}

// 模拟查询接口
const findCustomSetting = async (id: any) => {
  return new Promise(resolve => {
    resolve(props.patients)
  })
}

const admitPatient = (bed: any) => {
  emit('admit', bed)
}

const scanCode = (bed: any) => {
  emit('scan', bed)
}

const transferBed = (bed: any) => {
  emit('transfer', bed)
}

const discharge = (bed: any) => {
  emit('discharge', bed)
}
</script>
